import { View, Text, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';
import {Button, Loading, Navbar, Tabs, Toast} from '@taroify/core';
import {SettingOutlined, UserCircleOutlined} from '@taroify/icons';
import { useDispatchUser, useUserSelector } from "@/hooks/user";
import {AgentItemCard, CustomTabbar} from "@/components";
import {useDispatchGlobalState} from "@/hooks/global";
import {isLogin} from "@/utils/auth";
import {useEffect} from "react";
import './index.css';


export default function Profile() {
  const dispatchUser = useDispatchUser();
  const dispatchGlobal = useDispatchGlobalState();
  const userDetail = useUserSelector(state => state.user.user);
  const is_login = isLogin()

  useEffect(() => {
    if(!is_login){
      Taro.redirectTo({
        url: `/pages/auth/WxLogin/index`,
      });
    }
    dispatchUser.fetchUser();
    dispatchGlobal.changeTab('profile')
    console.log('Page loaded.');
  }, [is_login]);

  const handleUserInfoEdit = async () => {
    await Taro.redirectTo({
      url: `/pages/profile/userInfo/index`,
    });
  };

  const handleAgentCreate = ()=>{
    Toast.success("请前往数字教师创建平台！！！")
  }

  const handleAgentDiscover = async ()=>{
    await Taro.redirectTo({
      url: `/pages/tabs/discover/index`,
    });
  }

  const handleAppSet = async ()=>{
    await Taro.navigateTo({
      url: `/pages/profile/setting/index`,
    });
  }
  console.log(userDetail);
  const windowInfo = Taro.getWindowInfo();
  const statusBarHeight = windowInfo.statusBarHeight;

  return (
    <View style={{ height: '100vh', width: '100vw', backgroundColor: 'white' }}>
      {/* 导航栏 */}
      <Navbar
        fixed
        style={{
          paddingTop: `${(statusBarHeight || 0) + 50}rpx`,
          background: 'linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%)',
          boxShadow: '0 2rpx 10rpx rgba(0, 0, 0, 0.1)',
        }}
      >
        <Navbar.NavLeft icon={<SettingOutlined onClick={handleAppSet} size={25} color='black' />} />
        <Navbar.Title style={{ fontSize: '35rpx', color: 'black', fontWeight: 'bold' }}>
          {userDetail ? "个人主页" : "加载中..."}
        </Navbar.Title>
      </Navbar>
      <View style={{ paddingTop: `${(statusBarHeight || 0) + 150}rpx`, width: '100%', height: `calc(100% - ${(statusBarHeight || 0) + 250}rpx)`, overflow: 'auto' }}>
        <View style={{ width: '100%', height: `100%`, overflowY: 'auto' }}>
          {userDetail ? (
            <View style={{ height: '100%' }}>
              {/* 头像和用户信息 */}
              <View style={{ padding: '40rpx 0', display: 'flex', justifyContent: 'center', alignItems: 'center', flexDirection: 'column' }}>
                {userDetail.avatar !== null ? <Image
                  src={`${process.env.TARO_APP_BASE_URL}${userDetail.avatar}`}
                  style={{
                    width: '300rpx',
                    height: '300rpx',
                    objectFit: 'cover',
                    borderRadius: '50%',
                    boxShadow: '0 4rpx 20rpx rgba(0, 0, 0, 0.1)'
                  }}
                /> : <UserCircleOutlined size={120} />}
                <Text style={{ fontSize: '40rpx', fontWeight: 'bold', textAlign: 'center', marginTop: '20rpx' }}>
                  昵称：{userDetail.nickname}
                </Text>
              </View>

              {/* 编辑个人资料按钮 */}
              <View style={{ padding: '40rpx', display: 'flex', justifyContent: 'center' }}>
                <Button
                  onClick={handleUserInfoEdit}
                  style={{
                    background: 'linear-gradient(135deg, #6a11cb, #2575fc)',
                    color: '#fff',
                    borderRadius: '50rpx',
                    padding: '20rpx 60rpx',
                    boxShadow: '0 4rpx 10rpx rgba(0, 123, 255, 0.3)',
                  }}
                >
                  编辑个人资料
                </Button>
              </View>

              {/* 选项卡 */}
              <Tabs style={{ margin: '20rpx', borderRadius: '20rpx', overflow: 'hidden'}}>
                <Tabs.TabPane title='数字教师'>
                  <View style={{ padding: '10rpx', backgroundColor: '#fff' }}>
                    <Button
                      onClick={handleAgentCreate}
                      style={{
                        borderRadius: '30rpx',
                        width: '100%'
                      }}
                    >
                      去创作
                    </Button>
                  </View>
                  {userDetail.agents?.map((item, index) => (
                    <AgentItemCard
                      key={index}
                      agent={item}
                    />
                  ))}
                </Tabs.TabPane>
                <Tabs.TabPane title='收藏'>
                  <View style={{ padding: '10rpx', backgroundColor: '#fff' }}>
                    <Button
                      onClick={handleAgentDiscover}
                      style={{
                        borderRadius: '30rpx',
                        width: '100%'
                      }}
                    >
                      去发现
                    </Button>
                  </View>
                  {userDetail.add_agents?.map((item, index) => (
                    <AgentItemCard
                      key={index}
                      agent={item}
                    />
                  ))}
                </Tabs.TabPane>
              </Tabs>
            </View>
          ) : (
            <Loading type='spinner' />
          )}
        </View>
      </View>
      <CustomTabbar />
    </View>
  );
}
